<?php

namespace app\index\controller;

use app\index\model\Fake as ModelFake;
use app\BaseController;
use frame\lib\Db;

class Fake extends Base
{
    public function index()
    {
        $this->view('index');
    }
    public function list()
    {
        $fake = @$_GET['fake'];
        if (!empty($fake)) {
            $fake = trim($fake);
        }
        $list = ModelFake::list($fake);
        success($list);
    }
    public function del()
    {
        $id = @$_GET['id'];
        if (!$id) error('缺少参数ID', 201);
        $id = explode(',', $id);
        $res = Db::name('fake')->where(['adder_user_id' => $this->uid])->whereIn('id', $id)->delete();
        if ($res) success();
        error();
    }
    public function add()
    {
        $this->view('add');
    }
    public function doAdd()
    {
        $param = $_POST;
        if ($param['num']) {
            if ($param['type'] == 2) {
                if (!array_key_exists('vip_count', $param) || !array_key_exists('vip_type', $param)) {
                    error('缺少参数vip_count、vip_type', 201);
                }
            } else if ($param['type'] == 3) {
                if (!array_key_exists('score', $param)) error('缺少参数score', 201);
                if (!is_numeric($param['score'])) error('score类型错误');
                if ($param['score'] <= 0) error('积分值必须大于0');
            }
            ModelFake::add($param);
            success();
        }
        error('请将参数输入完整', 201);
    }
    public function use()
    {
        $fake = @$_GET['fake'];
        if (empty($fake)) error('卡密不能为空', 201);
        $has = Db::name('fake')->where(['status' => 0,'type' => 2, 'fake' => $fake, 'adder_user_id' => 0, 'delete_time' => 0])->find();
        if (!$has) error('卡密不存在');
        $res = Db::name('fake')->where(['fake' => $fake])->update(['status' => 1]);
        if ($res){
            $user = Db::name('user')->where(['id' => $this->uid])->find();
            $vip = getTime(3 , $user['vip_time']);
            $vip_time = $vip < time() ? getTime(2 , time() + $has['vip_time']) : getTime(2 , $vip + $has['vip_time'] );
            $res = Db::name('user')->where(['id' => $this->uid])->update(['vip_time' => $vip_time]);
            if($res) success();
        }
        error();
    }
}
